package com.qingzhuge.manager.security.support;

import com.qingzhuge.manager.dto.AdminLoginDto;
import com.qingzhuge.manager.entity.SysUser;
import com.qingzhuge.manager.security.token.MobileAuthenticationToken;
import com.qingzhuge.manager.security.token.UsernameAuthenticationToken;
import com.qingzhuge.manager.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.Set;

/**
 * @author zeroxiao
 * @date 2019/9/12 17:23
 * @description
 */
@Slf4j
@Component
public class MobileCodeAuthenticationProvider  implements AuthenticationProvider {
    @Autowired
    private ISysUserService userService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        UsernameAuthenticationToken token = (UsernameAuthenticationToken) authentication;
        String mobile = (token.getPrincipal() == null) ? "NONE_PROVIDED" : token.getName();
        String code = token.getCredentials();
        if (StringUtils.isEmpty(code)) {
            log.debug("验证码不能为空:[{}]",code);
            throw new BadCredentialsException("验证码不能为空");
        }
        AdminLoginDto dto = new AdminLoginDto();
        dto.setPhone(mobile);
        dto.setVerificationCode(code);
        dto.setCaptcha(token.getCode());
        SysUser user = userService.login(dto);
        if (user == null) {
            log.debug("账号不存在:[{}]",mobile);
            throw new UsernameNotFoundException("账号不存在");
        }
        MobileAuthenticationToken result = new MobileAuthenticationToken(userService.createUserDetails(user), code,token.getCode(), listUserGrantedAuthorities(user));
        result.setDetails(token.getDetails());
        return result;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return (MobileAuthenticationToken.class.isAssignableFrom(authentication));
    }

    private Set<GrantedAuthority> listUserGrantedAuthorities(SysUser user) {
        Set<GrantedAuthority> authorities = new HashSet<>();
        if (null == user) {
            return authorities;
        }
//        authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
        return authorities;
    }

}